package api

import (
	"api_getway/basic/config"
	__ "api_getway/basic/proto"
	"api_getway/handler/request"
	"api_getway/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
)

func AddGood(c *gin.Context) {
	var err error
	var req request.AddGoodReq

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	add, err := config.ShopClient.AddGood(c, &__.AddGoodReq{
		Title:    req.Title,
		TypesId:  req.TypesId,
		Price:    req.Price,
		Num:      req.Num,
		CookieId: req.CookieId,
		Image:    req.Image,
	})

	if !pkg.TestingStringV2(req.Title, "") {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "商品名称包含违规词！",
		})
		return
	}

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "商品名称包含违规词",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"goodsId": add.Id,
		"msg":     "商品添加成功",
	})
}

func AskLog(c *gin.Context) {
	var err error
	var req request.AskLogReq

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	log, err := config.ShopClient.AskLog(c, &__.AskLogReq{
		UserId:  req.UserId,
		GoodsId: req.GoodsId,
		Content: req.Content,
	})

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "已登录订单无效",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"goodsId": log.Id,
		"msg":     "咨询创建成功",
	})
}

func Order(c *gin.Context) {
	var err error
	var req request.OrderReq

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	order, err := config.ShopClient.Order(c, &__.OrderReq{
		UserId:  req.UserId,
		GoodsId: req.GoodsId,
	})

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "订单异常",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"goodsId": order.OrderSn,
		"msg":     "订单无异常",
	})
}
